package com.kujawnode.config.handler;

import com.kujawnode.result.R;
import com.kujawnode.utils.JSONUtils;
import com.kujawnode.utils.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @version 1.0
 * @Author kujaw
 * @Date 2025/7/9 15:08
 * @注释
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        R result = R.FAIL(exception.getMessage());

        //把R对象转换为json
        String resultJSON = JSONUtils.toJSON(result);

        //把R以JSON形式返回给前端
        ResponseUtils.write(response,resultJSON);
    }
}
